/**
 * 计算所有任务的最小/最大时间范围
 * 
 * @description 遍历所有任务节点的航点，找出最早和最晚的时间点
 * @param ganttData - 甘特图数据对象
 * @returns 时间范围对象 { min, max }，如果没有数据则返回 null
 */

import { computed, ComputedRef } from 'vue'
import { GanttData, TimeRange, TaskNode } from './types'

export function useMinMaxTime(ganttData: GanttData): ComputedRef<TimeRange | null> {
  return computed(() => {
    let minT = Number.MAX_VALUE
    let maxT = 0
    let hasData = false

    const traverseForMinMaxTime = (nodes: TaskNode[]) => {
      nodes.forEach(node => {
        if (node.waypoints && Array.isArray(node.waypoints)) {
          node.waypoints.forEach((wp) => {
            const t = new Date(wp.time.replace(/-/g, '/')).getTime()
            if (!isNaN(t)) {
              if (t < minT) minT = t
              if (t > maxT) maxT = t
              hasData = true
            }
          })
        }
        if (node.children) {
          traverseForMinMaxTime(node.children)
        }
      })
    }
    
    traverseForMinMaxTime(ganttData.rawTasks)

    if (!hasData) return null
    return { min: minT, max: maxT }
  })
}
